import { storage, pubsub } from '../utils';
import { zhCN } from './zhCN';
import { enUS } from './enUS';

export const locals = {
  'zh-CN': zhCN,
  'en-US': enUS
};

/**
 * 国际化处理
 */
class Language {
  constructor() {
    window.language = storage.local.get('language') || 'zh-CN';
    storage.local.set('language', window.language);
  }

  /**
   * 国际化语言
   * @param {string} name 字段名称
   * @param {object} data 模板参数：默认是undefined
   * @param {string} type 语言类型，默认是undefined
   */
  val(name, data, type) {
    if (!window.language) {
      window.language = storage.local.get('language') || 'zh-CN';
    }
    let str = locals[type || window.language][name] || 'not found';
    if (data) {
      for (let key in data) {
        str = str.replaceAll(`{{${key}}}`, data[key]);
      }
    }
    return str;
  }

  getLanguage() {
    return window.language || storage.local.get('language') || 'zh-CN';
  }

  setLanguage(type) {
    storage.local.set('language', type);
    window.language = type;
    // 更新视图
    pubsub.publish('setLanguage', type);
  }
}

export const language = new Language();
